<?php

class Requisition_model extends CI_Model 
{
    function __construct()
    {
        parent::__construct();
    }
	
	function get_requisitions($month = null, $year = null, $rr_number = null, $name = null)
	{
		$this->db->from('requisition');
		
		if($month)
		{
			$this->db->where('MONTH(date_created)', $month);
		}
		
		if($year)
		{
			$this->db->where('YEAR(date_created)', $year);
		}
		
		if($rr_number)
		{
			$this->db->where('rr_number LIKE \'%' . $rr_number . '%\'');
		}
	
		$query = $this->db->get();
		
		$result = $query->result();
		$requisitions = array();

		foreach($result as $r)
		{
			$this->db->select('*');
			$this->db->select('requisition_material.unit', 'unit');
			$this->db->from('requisition_material');
			$this->db->where('requisition_id', $r->id);
			$this->db->join('material', 'requisition_material.material_id = material.id');
			
			$query = $this->db->get();
			$materials = $query->result();
			
			$r->materials = $materials;
			$requisitions[] = $r;
		}
		
		return $requisitions;
	}
	
	function create($rr_number, $requestor_id, $department_id, $materials)	
	{
		$data['rr_number'] = $rr_number;
		$data['requestor_id'] = $requestor_id;
		$data['department_id'] = $department_id;
		$data['date_created'] = date('Y-m-d');
		
		$this->db->insert('requisition', $data);
		$id = $this->db->insert_id();
		
		foreach($materials as $material)
		{
			if($material['id'])
			{
				$data = array();
				$data['requisition_id'] = $id;
				$data['material_id'] = $material['id'];
				$data['quantity'] = $material['quantity'];
				$data['unit'] = $material['unit'];
				
				$this->db->insert('requisition_material', $data);
			}
			else
			{
			}
		}
	}
}